package com.wys.mall.server.controller;

import com.wys.mall.server.vo.LoginInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Package com.wys.mall.server.controller
 * @Author charlin
 * @Version: v1.0
 * @Date 2021-07-0714:08
 * @Copyright: 2021 www.wyscha.com Inc. All rights reserved.
 */
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token) {
        return redisTemplate.opsForValue().get(token);
    }

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url") String url, Model model, @CookieValue(value = "sso_token", required = false) String sso_token) {
        model.addAttribute("url", url);
        if (!StringUtils.isEmpty(sso_token)) {
            //说明有人登录
            return "redirect:" + url + "?token=" + sso_token;
        }
        //登录成功，跳转到原来页面
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(LoginInfoVo vo, HttpServletResponse response) {
        if (StringUtils.isEmpty(vo.getPassword())) {
            return "login";
        }
        String uuid = UUID.randomUUID().toString().replace("_", "");
        redisTemplate.opsForValue().set(uuid, vo.getUsername());
        Cookie cookie = new Cookie("sso_token", uuid);
        response.addCookie(cookie);
        //登录成功，跳转到原来页面
        return "redirect:" + vo.getUrl() + "?token=" + uuid;
    }
}
